<?php

namespace App\Model;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TrendsContent extends BaseModel
{
    protected $table = 'trends_content';
    protected $tableRecommend = 'trends_ad';
    protected $tableUser = 'user';
    protected $tableRoom = 'room';
    protected $primaryKey = 'content_id';
    public $timestamps = false;
    protected $connection = 'api';
    private $fields = ['content_id', 'user_id', 'c_content', 'c_imgs', 'c_video', 'c_voice', 'c_type', 'create_timestamp'];

    public function scopeCType($query, $type)
    {
        return $query->where('c_type', $type);
    }

    public function getCContentAttribute($value)
    {
        if (!$value) return '';
        $array = json_decode($value, true);
        $string = '';
        if ($array) {
            foreach ($array as $v) {
                if (is_array($v['mess'])) {
                    foreach ($v['mess'] as $vv) {
                        $string .= $vv['mess'] ?? '';
                    }
                } else {
                    $string .= $v['mess'] ?? '';
                }
            }
        }

        return $string;
    }

    public function getCImgsAttribute($value)
    {
        if (!$value) return [];
        $array = explode(',', $value);
        foreach ($array as &$img) {
            $img = config('kkaudio.oss_url') . $img;
        }
        unset($img);
        return $array;
    }

    public function getCVideoAttribute($value)
    {
        if (!$value) return '';
        return config('kkaudio.oss_url') . $value;
    }

    public function getCVoiceAttribute($value)
    {
        if (!$value) return '';
        return config('kkaudio.oss_url') . $value;
    }

    public function getCreateTimestampAttribute($value)
    {
        if (!$value) return 0;
        return date('Y-m-d H:i:s', $value);
    }

    public function user()
    {
        return $this->belongsTo(Number::class, 'user_id', 'user_id');
    }

    public function getList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $uuid = $request->input('uuid', '');
        $state = $request->input('status');
        $type = $request->input('type');
        $c_type = $request->input('c_type');
        $end_time = $request->input('end_date', '');


        $query = new self();
        if ($end_time) {
            $begin_date = strtotime($end_time[0]);
            $end_date = strtotime($end_time[1]);
            if ($begin_date && $end_date) $query = $query->whereBetween('create_timestamp', [$begin_date, $end_date]);
        }
        if ($state >= 0) $query = $query->where('status', $state);
        if ($type >= 0) $query = $query->where('type', $type);
        if ($c_type >= 0) $query = $query->where('c_type', $c_type);

        $number = new Number();
//        $number->getForbidList();
        $user_id = array_keys($number->forbidUser);
        if (!empty($user_id)) $query = $query->whereNotIn('user_id', $user_id);

        $query = $query->with(['trendsZpzyCount'])->whereHas('user', function ($query) use ($uuid) {
            $query->select(['user_id']);
            if ($uuid) $query->where('uuid', $uuid);
        })->where('is_delete', 0)
            ->orderBy('content_id', 'DESC')
            ->with(['user:user_id,uuid,nickname,portrait']);
        return $query->paginate($limit, ['*'], 'page', $page);
    }

    public function getTrendsFirst($id)
    {
        $query = new self();
        $query = $query->where('content_id', $id);
        $uuid = '';

        $number = new Number();
//        $number->getForbidList();
        $user_id = array_keys($number->forbidUser);
        if (!empty($user_id)) $query = $query->whereNotIn('user_id', $user_id);

        $query = $query->with(['trendsZpzyCount'])->whereHas('user', function ($query) use ($uuid) {
            $query->select(['user_id']);
            if ($uuid) $query->where('uuid', $uuid);
        })->where('is_delete', 0)
            ->orderBy('content_id', 'DESC')
            ->with(['user:user_id,uuid,nickname,portrait']);
        $res = $this->objToArray($query->first());

        if ($res && isset($res['c_type']) && $res['c_type']==7){
            $first = DB::connection('api')->table($this->table)->where('content_id', $id)->first();
            if ($first){
                $res['c_content'] = $first->c_content ?? '';
            }
        }

        $log = $this->getAuditLog($id);
        $res['audit_count'] = count($log);
        $res['audit_status'] = $log[$res['audit_count'] - 1]['status'] ?? 3;
        return $res;
    }

    public function countWaitAudit()
    {
        return $this->where('state', 0)->count();
    }

    public function updateData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/trends/update', $data, 'urlencoded', 'GET');
    }

    public static function deleteAllData($id)
    {
        return static::where('user_id', $id)->update(['is_delete' => 1]);
    }

    public function searchTrends($uuid = 0)
    {
        $sql = "select content_id,c.user_id,nickname,uuid ,c_content,c_voice,c_cover from zb_trends_content c left join  zb_user u on c.user_id = u.user_id where c_type = 4 and is_delete = 0 and uuid LIKE '$uuid%'";
        return DB::connection('api')->select($sql);
    }

    public function updateTrend($content_id, $type)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/trends/set_type', ['content_id' => $content_id, 'type' => $type], 'urlencoded', 'GET');
    }

    public function trendsZpzyCount()
    {
        return $this->hasOne(TrendsZpzyCount::class, 'content_id', 'content_id');
    }

    /**
     * 审核
     * @param $content_id
     * @param $state 0 待审核;1 已审核
     * @return mixed
     */
    public function auditTrend($content_id, $state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/trends/audit', ['content_id' => $content_id, 'state' => $state], 'urlencoded', 'GET');
    }

    public function switchState($state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/trends/audit_switch', ['status' => $state], 'urlencoded', 'GET');
    }

    public function getSwitchState()
    {
        return curl_request(getKkaudioApiUrl() . '/inner/trends/audit_switch', [], 'urlencoded', 'GET');
    }

    public function trendsTopic()
    {
        return $this->belongsToMany(TrendsTopic::class, 'trends_topic_join', 'content_id', 'topic_id');
    }

    //查询审核记录
    public function getAuditLog($id)
    {
        $where['trend_id'] = $id;
        $res = $this->objToArray(DB::table('audit_trends_log')->where($where)
            ->leftJoin('users', 'users.id', '=', 'audit_trends_log.audit_id')
            ->orderBy('type', 'asc')->get(['*','audit_trends_log.created_at as check_time']));
        return $res;
    }

    public function createLog($id, $status, $type, $admin_id)
    {
        $data['trend_id'] = $id;
        $data['audit_id'] = $admin_id;
        $data['type'] = $type;
        $data['status'] = $status;
        $data['created_at'] = date("Y-m-d H:i:s", time());
        return DB::table('audit_trends_log')->insert($data);
    }

    public function getRecommendList(){
        $res = DB::connection('api')->table($this->tableRecommend)->get();
        $res = json_decode(json_encode($res),true);
        foreach ($res as &$r){
            if(!empty($r['target_id'])){
                if($r['type'] == 1){
                    $user =  DB::connection('api')->table($this->tableUser)->where('user_id' ,$r['target_id'])->first();
                    $r['name'] = $user->nickname ?? '';
                }else{
                    $room =  DB::connection('api')->table($this->tableRoom)->where('room_id' ,$r['target_id'])->first();
                    $r['name'] = $room->name ?? '';
                }
            }else{
                $r['name'] = '';
            }
            if($r['start_timestamp'] <= date('Y-m-d H:i:s') && $r['end_timestamp'] >= date('Y-m-d H:i:s')){
                $r['effect_status'] = '生效中';
            }else{
                $r['effect_status'] = '未生效';
            }
        }
        return $res;
    }

    public function createOrUpdateRecommend($data){
        return curl_request(getKkaudioApiUrl() . '/inner/trends/curdAd', $data, 'json', 'POST');
    }

    public function deleteRecommend($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/trends/delAd', $data, 'json', 'POST');
    }
}
